﻿//---------------------------------------------------------------------
// Author: Reinhard Lehrbaum
//
// Description: List authorized DHCP servers.
//
// Creation Date: 2006-12-20
//---------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.DirectoryServices;
using System.Management.Automation;
using System.Text.RegularExpressions;

namespace Pscx.Commands.DirectoryServices
{
    [Cmdlet(VerbsCommon.Get, "DhcpServer"),
     Description("Gets a list of authorized DHCP servers.")]
    public class GetDhcpServerCommand : Pscx.Commands.Internal.PscxDirectoryServiceCommandBase
    {
        protected override void ProcessRecord()
        {
            DirectoryEntry RootDSE = GetDirectoryEntry("LDAP://" + (!string.IsNullOrEmpty(FServer) ? FServer + "/" : "") + "RootDSE");
            DirectoryEntry ConfigContainer = GetDirectoryEntry("LDAP://" + (!string.IsNullOrEmpty(FServer) ? FServer + "/" : "") + "CN=NetServices,CN=Services," +
                RootDSE.Properties["configurationNamingContext"].Value);
            
            DirectorySearcher ConfigSearcher = new DirectorySearcher(ConfigContainer);
            ConfigSearcher.Filter = "(&(objectClass=dHCPClass))";

            foreach (SearchResult result in ConfigSearcher.FindAll())
            {
                DirectoryEntry server = GetDirectoryEntry(result.Path);

                if (server.Properties["dhcpServers"].Value != null)
                {
                    if (server.Properties["dhcpServers"].Value.GetType() == typeof(String))
                    {
                        ParseDHCP(server.Properties["dhcpServers"].Value.ToString());
                    }
                    else
                    {
                        if (server.Properties["dhcpServers"].Value.GetType() == typeof(Object[]))
                        {
                            ArrayList list = new ArrayList();
                            list.AddRange((Object[])server.Properties["dhcpServers"].Value);

                            foreach (string item in list)
                            {
                                ParseDHCP(item);
                            }
                        }
                    }
                }                
            }
        }

        private void ParseDHCP(string value)
        {
            MatchCollection mc;
            Regex r = new Regex(@"^i([^$]*)\$r([^$]*)\$f([^$]*)\$s([^$]*)\$");
            mc = r.Matches(value);

            for (int i = 0; i < mc.Count; i++)
            {
                // Server:  mc[i].Groups[4]
                // Address: mc[i].Groups[1]
                // ds:      mc[i].Groups[2]
                WriteObject(new DHCPServerInfo(mc[i].Groups[4].Value, mc[i].Groups[1].Value));
            }
        }
    }
}
